package com.heima.behavior.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.behavior.dtos.ReadBehaviorDto;
import com.heima.behavior.pojos.ApReadBehavior;
import com.heima.behavior.service.ApReadBehaviorService;
import com.heima.common.constans.HotArticleConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.mess.UpdateArticleMess;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.AppThreadLocalUtil;
import org.bson.types.ObjectId;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class ApReadBehaviorServiceImpl implements ApReadBehaviorService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;
    @Override
    public ResponseResult read(ReadBehaviorDto dto) {
        //1.参数校验
        if(dto.getArticleId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.获取登录用户id,
        ApUser apUser = AppThreadLocalUtil.getApUser();
        //如果没有登录，则不能执行以下步骤，游客身份
        if(apUser!=null && apUser.getId()==0){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //3.查询mongo中是否有数据，如果有，则更新次数和时间，如果没有，则新增数据
        ApReadBehavior apReadBehavior = mongoTemplate.findOne(Query.query(
                Criteria.where("userId").is(apUser.getId()).and("articleId").is(dto.getArticleId())
        ), ApReadBehavior.class);
        if(apReadBehavior!=null){
            apReadBehavior.setCount(apReadBehavior.getCount()+dto.getCount());
            apReadBehavior.setCreatedTime(new Date());
            mongoTemplate.save(apReadBehavior);
        }else {
            apReadBehavior=new ApReadBehavior();
            BeanUtils.copyProperties(dto,apReadBehavior);
            apReadBehavior.setCreatedTime(new Date());
            apReadBehavior.setUpdatedTime(new Date());
            apReadBehavior.setUserId(apUser.getId().longValue());
            apReadBehavior.setId(ObjectId.get().toHexString());
            apReadBehavior.setCount(1);
            mongoTemplate.insert(apReadBehavior);
        }

        UpdateArticleMess mess=new UpdateArticleMess();
        mess.setArticleId(dto.getArticleId());
        mess.setType(UpdateArticleMess.UpdateArticleType.VIEWS);
        mess.setAdd(1);
        //发送消息给kafka
        kafkaTemplate.send(HotArticleConstants.HOT_ARTICLE_SCORE_TOPIC, JSON.toJSONString(mess));

        return ResponseResult.okResult("阅读完成");
    }
}
